<template>
	<div style="height: calc(100vh - 30px); padding: 15px; background-color: white">
		<tiny-split v-model="split1" style="z-index: 9">
			<template #left>
				<div style="padding:5px;">
          <JButton icon="refresh" @click="getList">刷新</JButton>
          <div style="height: 10px"></div>
          <t-alert :closable="false" text="经办人列表" v-if="salesList.length > 0"></t-alert>
          <div style="padding-right: 10px; display: flex; margin-top: 20px; flex-wrap: wrap; flex-flow: wrap">
            <div :class="['item', currentSalesId === item.doId ? 'active' : '']" @click="chose(item)" v-for="(item, index) in salesList" :key="index">
              {{ item.doName }}
            </div>
          </div>
        </div>
			</template>
			<template #right>
        <j-grid
          ref="rplistRef"
          :remoteSort="false"
          v-model="sumBills"
          :columns="fields"
          all-fields
          trigger="manual"
          @cell-click="cellClick"
          @edit-closed="editClose"
        />
			</template>
		</tiny-split>
		<dorppop ref="dorpRef" @saveSuc="saveSuc" />
    <j-dialog v-model="showBill" title="增加应收票据" :z-index="9" :width="950" destroy-on-close>
      <div>
        <tiny-alert type="success">{{altRow.buName}}</tiny-alert>
      </div>
      <div style="margin-top: 20px;">
        <j-grid ref="altRef" :columns="altFields" v-model="altList" :height="600" click-row-to-select />
      </div>
      <div style="text-align: center;margin-top: 20px;">
        <JButton size="large" type="info" @click="altDone">确定选中</JButton>
      </div>
    </j-dialog>
	</div>
</template>
<script>
import tool from '@/utils/tool';
import dorppop from './dorppop.vue';
export default {
	name: 'ldsk',
	components: {  dorppop },
	data () {
		return {
			split1: 0.1,
			salesList: [],
			detailList: [],
      showBill: false,
			showAccount: false,
			currentSalesId: null,
			fields: [
				{ type: 'index', width: 40 },
				{ field: 'buName', title: '终端名称', width: 220,  align: 'left' ,filter: true,visible: true,
        },
				{ field: 'billDate', title: '票据日期', width: 100, visible: true,align: 'center' },
				{ field: 'billNo', title: '票号', width: 130, canClick: true, visible: true,},
				{ field: 'transTypeName', title: '业务类型', width: 90, visible: true,align: 'center'  },
				{ field: 'salesName', title: '业务员', width: 90,visible: true, align: 'center' },
				{ field: 'doName', title: '经办人', width: 90,visible: true,align: 'center' },
				{ field: 'arrearsReal', title: '应收金额', width: 100, subSum: true, formatter: 'formatMoney', align: 'right',visible: true, },
				{ field: 'leftAmount', title: '应收结余', width: 90, subSum: true, formatter: 'formatMoney', align: 'right',visible: true, },
				{
					field: 'nowCheck',
					title: '本次收款',
					width: 100,
					formatter: 'formatMoney',
					subSum: true,
					align: 'right',
					editor: { component: 'input', autoselect: true },visible: true,
				},
				{
					field: 'yhAmount',
					title: '收款优惠',
					width: 90,
					formatter: 'formatMoney',
					subSum: true,
					align: 'right',
					editor: { component: 'input', autoselect: true },visible: true,
				},
				{ field: 'ye', title: '结余', width: 100, subSum: true, formatter: 'formatMoney', align: 'right',visible: true, },
				{ field: 'createdAt', width: 90, title: '派单时间', align: 'right',fixed: 'right',visible: true, },
				{
					field: '',
					title: '操作',
					width: 120,
					filter: true,
					sortable: true,
          align: 'center',
					btns: [
						{
							id: 'verify',
							label: '审核',
							show: "row.transTypeName==='小计'",
							click: (row) => {
								this.verify(row);
							},
						},
            {
              id: 'add',
              label: '增加',
              show: "row.transTypeName==='小计'",
              click: (row) => {
                this.addBill(row);
              },
            },
            {
              id: 'del',
              label: '删除',
              show: "row.transTypeName!=='小计'",
              click: (row) => {
                this.del(row);
              },
            },
					],
				},
			],
      altFields: [
				{ type: 'index', width: 40 },
        { type: 'selection', width: 40,align: 'center' },
				{ field: 'buName', title: '终端名称', width: 220,  align: 'left' ,visible: true,},
				{ field: 'billDate', title: '票据日期', width: 100, visible: true,align: 'center' },
				{ field: 'billNo', title: '票号', width: 130, canClick: true, visible: true,filter:true},
				{ field: 'transTypeName', title: '业务类型', width: 90, visible: true,align: 'center' ,filter:true },
				{ field: 'salesName', title: '业务员', width: 90,visible: true, align: 'center' },
				{ field: 'totalAmount', title: '票据金额', width: 90, sum: true, formatter: 'formatMoney', align: 'right',visible: true, },
				{ field: 'arrearsReal', title: '应收结余', width: 90, sum: true, formatter: 'formatMoney', align: 'right',visible: true, },
			],
      altList: [],
      currentRow: {},
      accountInfo: {},
      currentSale: {},
      altRow: {}
		};
	},
	created() {
		this.getList();
	},
	computed: {
		sumBills() {
			let ret = [];
			let gp = tool.xe.groupBy(this.detailList, 'buId');
			for (let buId in gp) {
				let arr = gp[buId];
				for (let i = 0; i < arr.length; i++) {
					let row = tool.xe.clone(arr[i]);
					delete row._RID;
					// if (i > 0) row.buName = '';
					ret.push(row);
				}
				let yh = tool.xe.sum(arr, 'yhAmount');
				let rp = tool.xe.sum(arr, 'nowCheck');
				let ye = tool.xe.sum(arr, 'ye');

				let arrearsReal = tool.xe.sum(arr, 'arrearsReal');
				let leftAmount = tool.xe.sum(arr, 'leftAmount');
				// 最后一行加合计
				ret.push({
					buId: arr[0].buId,
					buName: arr[0].buName,
					transTypeName: '小计',
					arrearsReal: arrearsReal ? tool.xe.toFixed(arrearsReal, 2) : '',
					leftAmount: leftAmount ? tool.xe.toFixed(leftAmount, 2) : '',
					nowCheck: rp ? tool.xe.toFixed(rp, 2) : '',
					yhAmount: yh ? tool.xe.toFixed(yh, 2) : '',
					ye: ye ? tool.xe.toFixed(ye, 2) : '',
					createdAt: '',
				})
			}
			return ret;
		},
	},
	methods: {
		del(row) {
			tool.confirm('确定从派单中删除收款', '删除提示').then(() => {
				for (let i = 0; i < this.detailList.length; i++) {
					if (this.detailList[i].id === row.id) {
						tool.post('receipt/pddel', { id: row.id }).then((ret) => {
							if (ret.stat) {
								this.detailList.splice(i, 1);
							}
						});
					}
				}
			});
		},
    verify (row) {
      this.$refs.dorpRef.openDia(row, this.detailList)
    },
    altDone () {
      let list = this.$refs.altRef.getSelected()
      if(list.length === 0) return tool.err('至少选中一行')
      list.map(row => {
        row.nowCheck = row.leftAmount
        row.yhAmount = 0
        row.ye = 0
      })
      tool.post('receipt/addSavePdList', {list,doId: this.currentSale.doId,doName: this.currentSale.doName}).then(ret => {
        this.detailList = []
        this.chose(this.currentSale)
        this.showBill = false
      })
    },
    // 增加票据
    addBill (row) {
      this.showBill = true
      this.altRow = row
      this.altList = []
      tool.post('receipt/addPdList', {buId: row.buId}).then(ret => {
        if(ret.stat) {
          this.altList = ret.data.list
        }
      })
    },
		cellClick(cell) {
			let row = cell.row;
			let field = cell.column.property;
			if (field === 'nowCheck') {
				if (row.transTypeName !== '小计') {
					this.$refs.rplistRef.setActiveCell(row, field);
				}
			}
			if (field === 'yhAmount') {
				if (row.transTypeName !== '小计') this.$refs.rplistRef.setActiveCell(row, field);
			}
		},
		// 业务员列表
		getList() {
			tool.post('receipt/pdsales', { state: '收款中' }).then((ret) => {
				if (ret.stat) {
					this.salesList = ret.data;
					if (ret.data.length === 0) return tool.suc('没有进行中的收款');
				}
			});
		},
		editClose(cell) {
			let field = cell.column.property;
			let row = cell.row;
			let transType = row.transType;
			if (transType === 150602) {
				if (field === 'nowCheck') {
					if (cell.row.nowCheck) cell.row.nowCheck = -Math.abs(cell.row.nowCheck);
				}
				if (field === 'yhAmount') {
					if (cell.row.yhAmount) cell.row.yhAmount = -Math.abs(cell.row.yhAmount);
				}
			}
			let ye = tool.minus(row.leftAmount, row.nowCheck, row.yhAmount);
			cell.row.ye = ye ? ye : '';
			for (let i = 0; i < this.detailList.length; i++) {
				if (this.detailList[i].id === row.id) {
					this.detailList[i].nowCheck = cell.row.nowCheck;
					this.detailList[i].yhAmount = cell.row.yhAmount;
					this.detailList[i].ye = cell.row.ye;
				}
			}
		},
		chose(item) {
      this.currentSale = item
			this.currentSalesId = item.doId;
      this.detailList = []
			tool.post('receipt/pdlist', { doId: item.doId, state: '收款中' }).then((ret) => {
				if (ret.stat) {
					this.detailList = ret.data.list;
          setTimeout(() => {
            this.$refs.rplistRef.scrollToRow(this.detailList[0])
            let dom =  document.getElementsByClassName('tiny-grid__body')[0]
            dom.style="transform:translateY(0px);"
          },100)
				}
			});
		},
    saveSuc () {
      this.getList()
      this.chose(this.currentSale)
    }
	},
};
</script>
<style scoped lang="scss">
.item {
  border: 1px solid gray;
  padding: 5px 10px;
  border-radius: 2px;
  margin-right: 15px;
  margin-bottom: 15px;
  font-size: 12px;
  font-weight: bold;
  color: #434a54;
  &:hover {
    cursor: pointer;
    border-color: var(--colorLeftMenu);
  }
  &.active {
    background-color: var(--colorLeftMenu);
    color: white;
  }
}
</style>